import uuid
from typing import Dict, List

from flask import Flask, jsonify, request

app = Flask(__name__)

# 使用内存存储用户数据
users: Dict[str, dict] = {}


@app.route('/users', methods=['POST'])
def create_user():
    data = request.get_json()

    # 验证必要字段
    required_fields = ['name', 'age', 'email']
    if not all(field in data for field in required_fields):
        return jsonify({'error': '缺少必要字段'}), 400

    # 生成唯一ID
    user_id = str(uuid.uuid4())
    users[user_id] = {
        'id': user_id,
        'name': data['name'],
        'age': data['age'],
        'email': data['email']
    }

    return jsonify(users[user_id]), 201


@app.route('/users', methods=['GET'])
def get_users():
    return jsonify(list(users.values()))


@app.route('/users/<user_id>', methods=['GET'])
def get_user(user_id):
    if user_id not in users:
        return jsonify({'error': '用户不存在'}), 404
    return jsonify(users[user_id])


@app.route('/users/<user_id>', methods=['PUT'])
def update_user(user_id):
    if user_id not in users:
        return jsonify({'error': '用户不存在'}), 404

    data = request.get_json()
    required_fields = ['name', 'age', 'email']
    if not all(field in data for field in required_fields):
        return jsonify({'error': '缺少必要字段'}), 400

    users[user_id].update({
        'name': data['name'],
        'age': data['age'],
        'email': data['email']
    })

    return jsonify(users[user_id])


@app.route('/users/<user_id>', methods=['DELETE'])
def delete_user(user_id):
    if user_id not in users:
        return jsonify({'error': '用户不存在'}), 404

    del users[user_id]
    return '', 204


if __name__ == '__main__':
    app.run(debug=True)
